#ifndef _DINPUT_H
#define _DINPUT_H
#include <dinput.h>

#include "..\common\def.h"
#include "..\math\math.h"
#include "..\math\vector.h"
#include "..\engine\time.h"
#include "..\engine\error.h"
#include "..\engine\log.h"

/* Mouse defines */

class EE_EXPORT CDInput9Device
{
private:
	
	enum DeviceState { UNINITALIZED = 0, OK, LOST_FOCUS, FAILED }; 

	static const int KEYBOARD_BUFFER_SIZE = 256; 
	static const int MOUSE_BUFFER_SIZE = 16; 
	static const int MOUSE_DOWN = 0; 
	static const int MOUSE_UP = 1; 

	LPDIRECTINPUT8			m_pDInput; 
	LPDIRECTINPUTDEVICE8	m_pKeyboardDevice; 
	LPDIRECTINPUTDEVICE8	m_pMouseDevice; 
	DIDEVICEOBJECTDATA		m_mouseDataBuffer[CDInput9Device::MOUSE_BUFFER_SIZE]; 
	DeviceState				m_State; 

	/* Keyboard key state map */
	char					m_keyMap[CDInput9Device::KEYBOARD_BUFFER_SIZE]; 
	char					m_prevKeyMap[CDInput9Device::KEYBOARD_BUFFER_SIZE]; 

	/* Mouse state data */
	Vector2i				m_mousePos; 
	Vector2i				m_mouseDelta; 
	int						m_mouseBut[3]; 
	int						m_mouseWheel; 

	/* Methods */
	HRESULT					CreateDevices(void); 
	HRESULT					ReleaseDevices(void); 

	HRESULT					UpdateMouse(void); 
	HRESULT					UpdateKeyboard(void); 

	HRESULT	CreateKeyboardDevice(void); 
	HRESULT	CreateMouseDevice(void); 

	HRESULT					ReleaseKeyboardDevice(void); 
	HRESULT					ReleaseMouseDevice(void); 

	void				ResetKeyboardState(); 
	void				ResetMouseState(); 
public:
	CDInput9Device(); 
	virtual~CDInput9Device(void); 

	HRESULT			Update(void); 
	HRESULT			Release(void); 
	HRESULT			Initailize(void); 

	bool isKeyDown(const int key); 
	bool isKeyUp(const int key); 
	bool isKeyReleased(const int key); 
	bool isKeyPressed(const int key); 
	char* getKeyMap(void); 
	char* getPrevKeyMap(void); 

	inline Vector2i getMousePosition(void) { return m_mousePos;  }
	inline Vector2i getMouseDelta(void) { return m_mouseDelta;  }

	inline void getMousePosition(int *pX, int *pY)
	{ 
		if(pX) *pX = m_mousePos.x; 
		if(pY) *pY = m_mousePos.y;  
	}
	inline void getMouseDelta(int *pdX, int *pdY)
	{ 
		if(pdX) *pdX = m_mouseDelta.x; 
		if(pdY) *pdY = m_mouseDelta.y;  
	}
	inline bool	isMouseDown(unsigned int button) { return (m_mouseBut[button] == MOUSE_DOWN);  }
	inline bool isMouseUp(unsigned int button) { return (m_mouseBut[button] == MOUSE_UP);  }
	inline int getMouseWheel(void) { return m_mouseWheel;  }
}; 
#endif
